//
//  CheckoutViewController.m
//  CS Inventory Manager
//
//  Created by Ian Smith on 3/23/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "CheckoutViewController.h"
#import "AppDelegate.h"
#import "Item.h"
#import "Category.h"
#import "Type.h"
#import "CategoryViewController.h"
#import "PatronViewController.h"

@interface CheckoutViewController ()
@end

@implementation CheckoutViewController
@synthesize checkoutItems, checkoutTable, detailViewController;

///Basic init function, nothing added here
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

///This is the IBAction that the "Checkout" button is tied too.
/// Calls the checkout wizard
-(void)checkoutButton:(id)sender
{
    [self performSegueWithIdentifier:@"CheckOutWizard" sender:nil];
}

///This sends a refresh command to both the Ietms and the Patrons tab.
/// Because the information in this tab is dependent upon up-to-date information
/// from both other tabs, a manual refresh must be forced every time this tab appears
/// to make sure the data is displayed accurately
-(void)refreshAll:(id)sender {
    //Grab all of the tabs that the tab bar has (should be three)
    NSArray *tabs = self.tabBarController.viewControllers;
    NSLog(@"There are %d tabs", tabs.count);    //log message to make sure tabs are being grabbed
    //Single out the items tab and grab its views
    UINavigationController *temp = tabs[0];
    NSArray *views = temp.viewControllers;
    CategoryViewController *inventory = views[0]; //Stick a reference to the inventory view (only view under tab 0) in a temp pointer
    //Now grab the patrons tab and do the same thing
    temp = tabs[1];
    views = temp.viewControllers;
    PatronViewController *patrons = views[0];
    //Now use the temp pointers to send a refresh command to both tabs
    [inventory refreshXML:nil];
    [patrons refreshXML:nil];
}

//This function grabs the nested array of all Items and parses through it to find only the items that are currently checked-out
-(void)flatten:(id)sender {
    checkoutItems = [[NSMutableArray alloc] init];                                                  //Init the array
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];         //Grab the entire Item hierarchy
    NSLog(@"Checkout View Flattening pre-loaded Item hierarchy");
    for (int i = 0; i < appDelegate.categories.count; i++) {                                        //Iterate through all Categories
        Category *category = appDelegate.categories[i];
        for (int j = 0; j < category.types.count; j++) {                                            //Iterate through all Types
            Type *type = category.types[j];
            for (int k = 0; k < type.items.count; k++) {                                            //Iterate through all Items
                Item *item = type.items[k];
                if ([item isCheckedOut]) {                                                          //If item is checked out, add it to list for display
                    [checkoutItems addObject:item];
                    NSLog(@"Added %@ to check-out view", item.model);
                    NSLog(@"Now have %lu items!", (unsigned long)checkoutItems.count);              //Log the addition for reference and bug checking
                    
                }
            }
        }
    }
    NSLog(@"Finished flattening hierarchy!");
    [self.checkoutTable reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    //Need to refresh the arrays to make sure data is up to date
    [self refreshAll:nil];
    //Wait for the XML functions to retrieve data before rebuilding the table view
    [self performSelector:@selector(flatten:) withObject:self afterDelay:0.4];

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //Set up the Item DVC so that any selections made in the table view will display in the detail view properly
    self.detailViewController = (ItemDetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return checkoutItems.count;
}

//Set up the table view and what it will display
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    Item *item = checkoutItems[indexPath.row];
    cell.textLabel.text = item.model;
    if ([[[item checkoutActive] patrons] count] == 1) {
        //single patron
        cell.detailTextLabel.text = [[[[item checkoutActive] patrons] objectAtIndex:0] name];
    } else {
        //multiple patrons
        cell.detailTextLabel.text = @"Multiple Patrons";
    }
    
    
    return cell;
}

#pragma mark - Table view delegate
//What happens when a table cell is tapped
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Pass the tapped item to the Item DVC, so that its stats can be displayed in the detail view
    Item *object = checkoutItems[indexPath.row];
    self.detailViewController.detailItem = object;
}

@end
